package model

import (
	"stock/global"
)

type CategoryModel struct {
	Base
}

type SysCategory struct {
	Id        uint   `json:"id" gorm:"<-:false; primaryKey;column:id;type:int(11)"`
	Name      string `json:"name" gorm:"column:name;"`
	NameEn    string `json:"name_en" gorm:"column:name_en;"`
	Cover     string `json:"cover" gorm:"column:cover;"`
	ParentId  uint   `json:"parent_id" gorm:"column:parent_id;"`
	Sort      string `json:"sort" gorm:"column:sort;"`
	Status    uint8  `json:"status" gorm:"column:status;"`
	CreateAt  string `json:"create_at" gorm:"column:create_at;"`
	UpdatedAt string `json:"updated_at" gorm:"column:updated_at;"`
}

type RequestCategory struct {
	ParentId uint
	Status   uint8
}

type ResponseCategory struct {
	SysCategory
}

func (m *CategoryModel) TabName() string {
	return global.CONF.Mysql.Prefix + "sys_column"
}

func (m *CategoryModel) List(param RequestCategory) ([]SysCategory, error) {

	var category []SysCategory
	where := &SysCategory{}
	if param.ParentId != 0 {
		where.ParentId = param.ParentId
	}
	if param.Status != 0 {
		where.Status = param.Status
	}
	err := global.DB.Debug().Where(where).Order("id DESC").Find(&category)
	if err.Error != nil {
		return nil, err.Error
	}
	return category, nil
}

func (m *CategoryModel) Child(parentId uint) []uint {
	var categoryId []uint
	m.ChildHandle(parentId, &categoryId)
	return categoryId
}

func (m *CategoryModel) ChildHandle(parentId uint, categoryId *[]uint) {
	var category []SysCategory
	tx := global.DB.Debug().Where(SysCategory{ParentId: parentId}).Order("id DESC").Find(&category)
	categoryLen := len(category)
	if tx.Error == nil && categoryLen > 0 {
		for i := 0; i < categoryLen; i++ {
			m.ChildHandle(category[i].Id, categoryId)
		}
	} else {
		*categoryId = append(*categoryId, parentId)
	}
}
